package com.jaks.xpense;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.jaks.xpense.adapters.CheckBoxArrayAdapter;
import com.jaks.xpense.data.Tags;
import com.jaks.xpense.data.entities.Tag;
import com.jaks.xpense.data.entities.TagModel;
import com.jaks.xpense.utils.Globals;

public class SelectTagsActivity extends ListActivity implements OnClickListener {

	private Tags tags;
	private ArrayList<TagModel> tagsList;
	private ArrayAdapter<TagModel> adapter;

	private long[] selectedTagIds;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		tags = new Tags(this);
		selectedTagIds = null;

		setContentView(R.layout.selecttags);

		TextView selectTags = (TextView) findViewById(R.id.selectTagsText);
		selectTags.setOnClickListener(this);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			selectedTagIds = extras.getLongArray(Globals.SelectedTagIds);
		}
	}

	private void populate() {
		ArrayList<Tag> allTags = tags.readAllToList();

		tagsList = new ArrayList<TagModel>();
		for (Tag tag : allTags) {
			TagModel model = new TagModel(tag);
			tagsList.add(model);

			if (selectedTagIds != null) {
				for (long id : selectedTagIds) {
					if (model.getId() == id) {
						model.setSelected(true);
						break;
					}
				}
			}
		}

		adapter = new CheckBoxArrayAdapter(this, R.layout.tagselectrow,
		    R.id.rowTagText, R.id.rowCheckBox, tagsList);
		setListAdapter(adapter);
	}

	@Override
	protected void onStart() {
		super.onStart();
		populate();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		tags.close();
	}

	@Override
	public void onClick(View v) {

		long[] selectedIds = null;
		String[] selectedNames = null;
		int count = 0;

		for (TagModel model : tagsList) {
			if (model.isSelected())
				count++;
		}

		if (count > 0) {
			int index = 0;
			selectedIds = new long[count];
			selectedNames = new String[count];

			for (TagModel model : tagsList) {
				if (model.isSelected()) {
					selectedIds[index] = model.getId();
					selectedNames[index] = model.getName();
					index++;
				}
			}
		}

		Intent result = new Intent();
		result.putExtra(Globals.SelectedTagIds, selectedIds);
		result.putExtra(Globals.SelectedTagNames, selectedNames);
		setResult(RESULT_OK, result);
		finish();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		boolean selected = tagsList.get(position).isSelected();
		tagsList.get(position).setSelected(!selected);
		adapter.notifyDataSetChanged();
	}
}
